//
//  SLStatusPictureView.swift
//  langligelang
//
//  Created by 秦－政 on 2016/10/28.
//  Copyright © 2016年 pete. All rights reserved.
//

import UIKit
import SDWebImage
// cell 可重用标识符
private let pictureViewCellIdentifier = "pictureViewCellIdentifier"
// cell 间距
private let cellMargin: CGFloat = 5
// cell 宽高
private let cellWH = CGFloat(Int((SLSCREENW - 20 - cellMargin*2)/3))

class SLStatusPictureView: UICollectionView {

    // 定义属性-> 数组
    var picUrls:[SLPictureInfoModel]?{
        didSet{
            // 赋值 得到配图的大小
//            let size = dealScaleSize(count: picUrls?.count ?? 0)
//            // 设置约束 更新 自己的大小
//            self.snp_updateConstraints { (make) in
//                make.size.equalTo(size)
//            }
            dealScaleSize(count: picUrls?.count ?? 0)
            // 刷新UI
            reloadData()
            
        }
        
        
    }
    // 计算配图的尺寸
    func dealScaleSize(count: Int) {
        // 如果是单张
        if count == 1 {
            // 获取key
            let key = picUrls?.first?.thumbnail_pic ?? ""
            // 获取Image 从缓存中获取
            let image = SDWebImageManager.shared().imageCache.imageFromDiskCache(forKey: key)
            // 因为SDWebImage 下载图片可能因为外界影响导致图图片下载不成功 所以说 防止 image == nil  我们需要做判断
            if image != nil {
                let result1 = Int(image!.size.height)
                let result2 = Int(image!.size.width)
                let resultSize = CGSize(width: result2, height: result1)
//                print("------")
//                print(resultSize)
//                print("xxxxx")
                // 更新约束
                self.snp_updateConstraints(closure: { (make) in
                    make.size.equalTo(resultSize)
                })
               
                // 设置 itemSize
                let layout = self.collectionViewLayout as! UICollectionViewFlowLayout
                layout.itemSize = resultSize
                 layoutIfNeeded()
                return
            }
        }
        
        // 列数和行数
        let col = count >= 3 ? 3 : count
        let row = (count - 1)/3 + 1
        // 最终宽和高
        let w = CGFloat(col) * cellWH + CGFloat(col - 1)*cellMargin
        let h = CGFloat(row) * cellWH + CGFloat(row - 1)*cellMargin
//        print("sssssss")
//        print(w,h)
//        print("sssssggggg")
        // 更新约束
        self.snp_updateConstraints(closure: { (make) in
            make.size.equalTo(CGSize(width: w, height: h))
        })
        
        // 设置 itemSize
        let layout = self.collectionViewLayout as! UICollectionViewFlowLayout
        layout.itemSize = CGSize(width: cellWH, height: cellWH)
        layoutIfNeeded()
    }

    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        super.init(frame: frame, collectionViewLayout: UICollectionViewFlowLayout())
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    // MARK: - 设置视图
    private func setupUI(){
        // 得到 layout
        let layout = self.collectionViewLayout as! UICollectionViewFlowLayout
        // 设置 itemSize
        layout.itemSize = CGSize(width: cellWH, height: cellWH)
        // 设置间距
        layout.minimumLineSpacing = cellMargin
        layout.minimumInteritemSpacing = cellMargin
        // 设置代理
        dataSource = self
        // 注册Cell
        register(SLStatusPictureViewCell.self, forCellWithReuseIdentifier: pictureViewCellIdentifier)
 
    }

}
extension SLStatusPictureView: UICollectionViewDataSource{
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return picUrls?.count ?? 0
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
     let cell = collectionView.dequeueReusableCell(withReuseIdentifier: pictureViewCellIdentifier, for: indexPath) as! SLStatusPictureViewCell
        cell.picUrl = picUrls![indexPath.item]
        return cell
    }
    
}
class SLStatusPictureViewCell: UICollectionViewCell {
    // 定义一个属性攻外界赋值
    var picUrl: SLPictureInfoModel?{
        didSet{
            // 赋值
            bgImageView.sl_setImage(withUrlString: picUrl?.thumbnail_pic, placeholderImgName: "timeline_image_placeholder")
            if picUrl?.thumbnail_pic?.hasSuffix(".gif") == true{
                // 动图显示gif图标
                gifImageView.isHidden = false
            } else {
                // 非动图隐藏图标
                gifImageView.isHidden = true
            }
        }
    }
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    private func setupUI(){
//        backgroundColor = SLRandomColor()
        // 添加控件
        contentView.addSubview(bgImageView)
        contentView.addSubview(gifImageView)
        // 约束
        bgImageView.snp_makeConstraints { (make) in
            make.edges.equalTo(contentView)
        }
        gifImageView.snp_makeConstraints { (make) in
            make.bottom.equalTo(bgImageView)
            make.trailing.equalTo(bgImageView)
        }
    }
        // 懒加载控件
    private lazy var bgImageView:UIImageView = {
        let view = UIImageView(imgName: "timeline_image_placeholder")
        // 显示图片样式
        view.contentMode = .scaleAspectFill
        view.layer.masksToBounds = true
        return view
    }()
    //  gif 图片
    private lazy var gifImageView: UIImageView = {
        let imageView = UIImageView(image: UIImage(named: "timeline_image_gif"))
        return imageView
    }()
}
